package com.ay.selfservicemachine.http;

import android.text.TextUtils;

import com.ay.selfservicemachine.utils.JsonUtils;
import com.honghea.rxhttp.DefaultClientFactory;
import com.honghea.rxhttp.DefaultRetrofitFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;

public class HttpUtils {


    public static HttpResult mapperResult(String responseBody) throws JSONException {
        HttpResult result = new HttpResult();
        JSONObject jsonObject = new JSONObject(responseBody);
        result.setSTS(jsonObject.optBoolean("STS"));
        result.setCODE(jsonObject.optInt("CODE"));
        result.setMSG(jsonObject.optString("MSG"));
        result.setDATA(jsonObject.optString("DATA"));
        return result;
    }

    public static <T> T mapperResult(String responseBody, Class<T> tClass) throws JSONException {
        JSONObject jsonObject = new JSONObject(responseBody);
        return JsonUtils.fromJson(jsonObject.optString("DATA"), tClass);
    }

    public static <T> List<T> mapperListResult(String responseBody) throws JSONException {
        JSONObject jsonObject = new JSONObject(responseBody);
        return JsonUtils.fromJson(jsonObject.optString("DATA"));
    }

    public static boolean isWifiProxy() {
        String proxyAddress;
        int proxyPort;
        proxyAddress = System.getProperty("http.proxyHost");
        String portStr = System.getProperty("http.proxyPort");
        proxyPort = Integer.parseInt((portStr != null ? portStr : "-1"));
        return (!TextUtils.isEmpty(proxyAddress)) && (proxyPort != -1);
//        return false;
    }

    private final OkHttpClient client;

    private HashMap<String, Retrofit> retrofitHashMap;


    private static volatile HttpUtils mInstance;

    private HttpUtils(OkHttpClient client) {
        this.client = client;
        this.retrofitHashMap = new HashMap<>();
    }

    public static HttpUtils getInstance() {
        if (mInstance == null) {
            synchronized (HttpUtils.class) {
                if (mInstance == null) {
                    mInstance = new HttpUtils(new DefaultClientFactory().provide());
                }
            }
        }
        return mInstance;
    }

    public void buildBaseUrl(String baseUrl) {
        if (!retrofitHashMap.containsKey(baseUrl)) {
            retrofitHashMap.put(baseUrl, new DefaultRetrofitFactory().provide(client, baseUrl));
        }
    }

    public Retrofit getRetrofit(String baseUrl) {
        if (retrofitHashMap.containsKey(baseUrl)) {
            return retrofitHashMap.get(baseUrl);
        } else {
            buildBaseUrl(baseUrl);
            return retrofitHashMap.get(baseUrl);
        }
    }


}
